<template>
  <div class="workorder-create-container">
    <div class="header-section">
      <div class="title-section">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/workorder' }">工单列表</el-breadcrumb-item>
          <el-breadcrumb-item>创建工单</el-breadcrumb-item>
        </el-breadcrumb>
        <h1 class="page-title">创建工单</h1>
      </div>
      <div class="action-buttons">
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
      </div>
    </div>

    <div class="content-section">
      <el-card class="form-card">
        <el-form 
          ref="formRef" 
          :model="workOrderForm" 
          :rules="rules"
          label-width="120px"
          label-position="top"
        >
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="工单标题" prop="title">
                <el-input v-model="workOrderForm.title" placeholder="请输入工单标题" />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="工单类型" prop="typeId">
                <el-select 
                  v-model="workOrderForm.typeId" 
                  placeholder="请选择工单类型" 
                  class="full-width"
                >
                  <el-option 
                    v-for="item in typeOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="优先级" prop="priority">
                <el-select 
                  v-model="workOrderForm.priority" 
                  placeholder="请选择优先级"
                  class="full-width"
                >
                  <el-option :value="1" label="低" />
                  <el-option :value="2" label="中" />
                  <el-option :value="3" label="高" />
                  <el-option :value="4" label="紧急" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="工单内容" prop="content">
                <el-input 
                  v-model="workOrderForm.content" 
                  type="textarea" 
                  :rows="10" 
                  placeholder="请详细描述问题或需求"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="24">
              <el-form-item label="上传附件">
                <el-upload
                  action=""
                  :http-request="uploadFile"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  multiple
                  :limit="5"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
                >
                  <el-button type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      文件大小不超过10MB
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { workOrder as workOrderApi } from '@/api'
import { useStore } from 'vuex'

export default {
  name: 'WorkOrderCreate',
  setup() {
    const router = useRouter()
    const store = useStore()
    const formRef = ref(null)
    const loading = ref(false)
    const fileList = ref([])
    const uploadedAttachments = ref([])
    
    // 表单数据
    const workOrderForm = reactive({
      title: '',
      typeId: null,
      priority: 2,
      content: ''
    })
    
    // 表单验证规则
    const rules = {
      title: [
        { required: true, message: '请输入工单标题', trigger: 'blur' },
        { min: 5, max: 100, message: '标题长度在5-100个字符之间', trigger: 'blur' }
      ],
      typeId: [
        { required: true, message: '请选择工单类型', trigger: 'change' }
      ],
      priority: [
        { required: true, message: '请选择优先级', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入工单内容', trigger: 'blur' },
        { min: 10, message: '内容不能少于10个字符', trigger: 'blur' }
      ]
    }
    
    // 选项数据
    const typeOptions = ref([])
    
    // 获取工单类型选项
    const getTypeOptions = async () => {
      try {
        console.log('正在调用获取工单类型API...');
        const res = await workOrderApi.getWorkOrderTypes()
        console.log('工单类型API响应:', res);
        if (res.data && res.data.code === 200) {
          typeOptions.value = res.data.data || []
          console.log('成功获取工单类型，数量:', typeOptions.value.length);
          if (typeOptions.value.length === 0) {
            console.warn('获取到的工单类型列表为空');
          }
        } else {
          console.error('获取工单类型失败，返回码:', res.data?.code, '消息:', res.data?.message);
          ElMessage.error(res.data?.message || '获取工单类型失败')
        }
      } catch (error) {
        console.error('获取工单类型失败', error.response?.data || error.message || error);
        let errorMsg = '获取工单类型失败';
        if (error.response) {
          errorMsg += `: ${error.response.status} ${error.response.statusText}`;
        }
        ElMessage.error(errorMsg)
      }
    }
    
    // 文件上传相关方法
    const uploadFile = async (options) => {
      try {
        const formData = new FormData()
        formData.append('file', options.file)
        
        // 工单ID在创建后才会有，先把文件存起来
        const fileInfo = {
          name: options.file.name,
          size: options.file.size,
          file: options.file
        }
        
        uploadedAttachments.value.push(fileInfo)
        options.onSuccess()
        
        ElMessage.success('文件已添加，将在工单创建后上传')
      } catch (error) {
        console.error('文件上传失败', error)
        options.onError()
        ElMessage.error('文件添加失败')
      }
    }
    
    const handlePreview = (file) => {
      console.log('预览文件', file)
    }
    
    const handleRemove = (file, fileList) => {
      uploadedAttachments.value = uploadedAttachments.value.filter(item => item.name !== file.name)
      console.log('移除文件', file, fileList)
    }
    
    const handleExceed = (files, fileList) => {
      ElMessage.warning(`最多同时上传5个文件，当前已选择${fileList.length}个文件`)
    }
    
    const beforeRemove = (file) => {
      return ElMessageBox.confirm(`确定移除 ${file.name}？`)
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            // 获取当前登录用户信息，优先使用Vuex中的用户信息
            const userInfo = store.getters.currentUser || JSON.parse(localStorage.getItem('user')) || {}
            console.log('获取到的用户信息:', userInfo)
            
            // 创建工单数据，添加创建者信息
            const workOrderData = {
              ...workOrderForm,
              creatorId: userInfo.id,  // 添加创建者ID
              creatorName: userInfo.realName || userInfo.username,  // 添加创建者名称
              creatorPhone: userInfo.phone || '',  // 添加创建者电话
              statusId: 1  // 显式设置初始状态为待处理(1)
            }
            
            console.log('提交的工单数据:', workOrderData)
            const res = await workOrderApi.createWorkOrder(workOrderData)
            
            if (res.data && res.data.code === 200) {
              ElMessage.success('创建工单成功')
              
              // 如果有附件，上传附件
              if (uploadedAttachments.value.length > 0) {
                const orderId = res.data.data.id
                
                // 上传所有附件
                for (const attachment of uploadedAttachments.value) {
                  const formData = new FormData()
                  formData.append('file', attachment.file)
                  formData.append('orderId', orderId)
                  
                  try {
                    await workOrderApi.uploadWorkOrderAttachment(formData)
                  } catch (error) {
                    console.error('附件上传失败', error)
                  }
                }
              }
              
              router.push('/workorder')
            } else {
              ElMessage.error(res.data?.message || '创建工单失败')
            }
          } catch (error) {
            console.error('创建工单失败', error)
            if (error.response && error.response.data) {
              ElMessage.error(`创建工单失败: ${error.response.data.message || error.message}`)
            } else {
              ElMessage.error(`创建工单失败: ${error.message || '未知错误'}`)
            }
          } finally {
            loading.value = false
          }
        } else {
          return false
        }
      })
    }
    
    // 返回列表页
    const goBack = () => {
      router.push('/workorder')
    }
    
    onMounted(() => {
      getTypeOptions()
    })
    
    return {
      formRef,
      workOrderForm,
      rules,
      loading,
      typeOptions,
      fileList,
      uploadedAttachments,
      submitForm,
      goBack,
      uploadFile,
      handlePreview,
      handleRemove,
      handleExceed,
      beforeRemove
    }
  }
}
</script>

<style scoped>
.workorder-create-container {
  padding: 24px;
  background-color: #f9fafb;
  min-height: calc(100vh - 60px);
}

/* 标题区域 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.title-section {
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 32px;
  font-weight: 300;
  color: #262626;
  margin: 8px 0 0;
  letter-spacing: -0.5px;
}

/* 表单区域 */
.content-section {
  margin-bottom: 24px;
}

.form-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.full-width {
  width: 100%;
}

/* 上传区域样式 */
.el-upload {
  width: 100%;
}

.el-upload__tip {
  line-height: 1.2;
  margin-top: 8px;
  color: #909399;
}
</style> 
 